package com.dlc.video;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import android.widget.VideoView;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MyVideoView extends VideoView {

    private int curPosition = 0;//当前播放地址

    private Context context;

    private List<String> videoList = new ArrayList<>();

    private Handler mHandler = new Handler();

    private String downloadPath;

    private boolean isAutoStop = false;//播放到最后一个视频后.是否停止

    private VideoStateListener mVideoStateListener;


    private FileDownloadListener fileDownloadListener = new FileDownloadListener() {
        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            Log.i("Jim", "pending");
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            Log.i("Jim", "progress");
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            Log.i("Jim", "视频下载完成");
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            Log.i("Jim", "视频暂停");
        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            Log.i("Jim", "下载视频error:" + e.getMessage());
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            Log.i("Jim", "下载视频warn");
        }
    };

    public MyVideoView(Context context) {
        this(context, null, 0);
    }

    public MyVideoView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        File file = context.getExternalFilesDir("download_video");
        if (file == null) {
            throw new NullPointerException("no files found");
        }
        downloadPath = file.getPath() + "/";
        FileDownloader.setup(context);
        setListener();
    }


    public void setAutoStop(boolean isAutoStop) {
        this.isAutoStop = isAutoStop;
    }

    public void setVideoStateListener(VideoStateListener mVideoStateListener) {
        this.mVideoStateListener = mVideoStateListener;
    }

    /**
     * 设置视频地址数组
     *
     * @param list
     */
    public void setList(List<String> list) {
        //如果设置的数组跟之前的数组不一样.则重新设置.否则无效
//        if(!(videoList.containsAll(list) && list.containsAll(videoList))){
        this.videoList = list;
        curPosition = 0;
        startPlay();
//        }
    }


    /**
     * 开始播放
     */
    public void startPlay() {
        if (videoList.size() != 0) {
            String fileName = videoList.get(curPosition).substring(videoList.get(curPosition).lastIndexOf("/") + 1);
            File downloadFile = new File(downloadPath);
            if (!downloadFile.exists()) {
                downloadFile.mkdirs();
            }
            File file = new File(downloadPath + fileName);
            //查看本地是否已经下载过,已经下载过.则播放本地视频,否则就一边播放一遍下载
            if (file.exists()) {
                Log.i("Jim", "本地已经存在视频了");
                setVideoPath(downloadPath + fileName);
            } else {
                Log.i("Jim", "本地没有该视频.开始下载");
                setVideoURI(Uri.parse(videoList.get(curPosition)));
                //下载视频
                FileDownloader.getImpl().create(Uri.decode(videoList.get(curPosition))).setPath(downloadPath + fileName).setListener
                        (fileDownloadListener).setAutoRetryTimes(2).start();
            }
            setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    start();
                }
            });
        }
    }

    /**
     * 设置监听
     */
    private void setListener() {
        setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                curPosition++;
                if(isPlaying()){

                }
                if (curPosition >= videoList.size()) {
                    curPosition = 0;
                    if (!isAutoStop) {
                        startPlay();
                    } else {
                        mVideoStateListener.playEnd();
                    }
                } else {
                    startPlay();
                }
            }
        });
        setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
                    //媒体服务器挂掉了。此时，程序必须释放MediaPlayer 对象，并重新new 一个新的。
                    Toast.makeText(context, "网络服务错误", Toast.LENGTH_LONG).show();
                } else if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
                    if (extra == MediaPlayer.MEDIA_ERROR_IO) {
                        //文件不存在或错误，或网络不可访问错误
                        Toast.makeText(context, "网络文件错误", Toast.LENGTH_LONG).show();
                    } else if (extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT) {
                        //超时
                        Toast.makeText(context, "网络超时", Toast.LENGTH_LONG).show();
                    }
                }
                //报错之后,5秒钟后播放下一个视频
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        curPosition++;
                        if (curPosition >= videoList.size()) {
                            curPosition = 0;
                            if (!isAutoStop) {
                                startPlay();
                            }
                        } else {
                            startPlay();
                        }
                    }
                }, 5000);

                return true;
            }
        });

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getDefaultSize(0, widthMeasureSpec);
        int height = getDefaultSize(0, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }


    public interface VideoStateListener {
        void playEnd();
    }

}
